#ifndef __COMM_HPP_
#define __COMM_HPP_

#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>

#define PATHNAME "."
#define PROJ_ID 0x666

// 共享内存的大小，一般建议是4KB的整数倍
// 系统分配共享内存是以4KB为单位的！ --- 内存划分内存块的基本单位Page
#define MAX_SIZE 4096 // --- 内核给你的会向上取整， 内核给你的，和你能用的，是两码事

key_t getkey()
{
    key_t key = ftok(PATHNAME, PROJ_ID);
    if (key == -1)
    {
        std::cerr << "error" << strerror(errno) << std::endl;
        exit(1);
    }

    return key;
}

int getShmHelper(key_t key, int flags)
{
    int shmid = shmget(key, MAX_SIZE, flags);
    if (shmid < 0)
    {
        std::cerr << errno << ":" << strerror(errno) << std::endl;
        exit(2);
    }

    return shmid;
}

int getShm(key_t key)
{
    return getShmHelper(key, IPC_CREAT);
}

int createShm(key_t key)
{
    return getShmHelper(key, IPC_CREAT | IPC_EXCL | 0600);
}

void *attachShm(int shmid)
{
    void *mem = shmat(shmid, nullptr, 0);
    if ((long long)mem == -1L)
    {
        std::cerr << "shmat:" << errno << ":" << strerror(errno) << std::endl;
        exit(3);
    }

    return mem;
}

void detachShm(void *start)
{
    if (shmdt(start) == -1)
    {
        std::cerr << "shmdt:" << errno << ":" << strerror(errno) << std::endl;
    }
}

void delShm(int shmid)
{
    if (shmctl(shmid, IPC_RMID, nullptr) == -1)
    {
        std::cerr << "shmctl:" << errno << ":" << strerror(errno) << std::endl;
    }
}
#endif